<template xmlns:background-color="http://www.w3.org/1999/xhtml">
  <a-row :gutter="10">
    <a-col :md="12" :sm="24" >
      <a-card :bordered="false">
        <!-- 按钮操作区域 -->
        <a-row style="margin-left: 14px">
<!--          <a-button @click="handleAdd(2)" type="primary">添加项目区域</a-button>-->
          <a-button @click="handleAddProject" type="primary">添加项目区域</a-button>
<!--          <a-button type="primary" icon="download" @click="handleExportXls('区域信息')">导出</a-button>-->
          <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
            <a-button type="primary" icon="import">导入</a-button>
          </a-upload> -->
          <a-button title="删除多条数据" @click="batchDel" type="default">批量删除</a-button>
          <span style='margin-left: 10px; color: blue'>蓝色表示区域</span>
          <!--<a-button @click="refresh" type="default" icon="reload" :loading="loading">刷新</a-button>-->
        </a-row>
        <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
          <!-- 区域树-->
          <a-col :md="10" :sm="24">
            <template>
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
               <span style="user-select: none">
            <a-tree
              checkable
              multiple
              @select="onSelect"
              @check="onCheck"
              @rightClick="rightHandle"
              :selectedKeys="selectedKeys"
              :checkedKeys="checkedKeys"
              :treeData="areaTree"
              :checkStrictly="true"
              :expandedKeys="iExpandedKeys"
              :autoExpandParent="autoExpandParent"
              @expand="onExpand">
              <template #title="item">
                    <span v-if="item.isArea==1" style="color:blue">{{item.title}}</span>
                    <span v-else>{{item.title}}</span>
              </template>
            </a-tree>
                </span>
                <!--新增右键点击事件,和增加添加和删除功能-->
                <a-menu  slot="overlay" >
                  <a-menu-item v-show='isArea' @click="bindProject" key="1">绑定项目</a-menu-item>
                  <a-menu-item v-show='isArea' @click="changeName" key="4">重命名</a-menu-item>
                  <a-menu-item @click="handleDelete" key="2">删除</a-menu-item>
                  <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </a-col>
        </div>
      </a-card>
    </a-col>
    <area-modal ref="areaModal" @ok="loadTree"></area-modal>
    <select-project-modal ref="selectProjectModal" @ok="finish"></select-project-modal>
  </a-row>
</template>
<script>
  import AreaModal from './modules/AreaModal'
  import pick from 'lodash.pick'
  import {queryAreaTreeList, searchByKeywordsArea, deleteByDepartId} from '@/api/api'
  import { httpAction, deleteAction, postAction } from '@/api/manage'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import SelectProjectModal from '@views/system/modules/SelectProjectModal'
  // 表头
  const columns = [
    {
      title: '机构名称',
      dataIndex: 'departName'
    },
    {
      title: '机构类型',
      align: 'center',
      dataIndex: 'orgType'
    },
    {
      title: '机构编码',
      dataIndex: 'orgCode',
    },
    {
      title: '手机号',
      dataIndex: 'mobile'
    },
    {
      title: '传真',
      dataIndex: 'fax'
    },
    {
      title: '地址',
      dataIndex: 'address'
    },
    {
      title: '排序',
      align: 'center',
      dataIndex: 'departOrder'
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'action',
      scopedSlots: {customRender: 'action'}
    }
  ]
  export default {
    name: 'DepartList',
    mixins: [JeecgListMixin],
    components: {
      SelectProjectModal,
      AreaModal
    },
    data() {
      return {
        iExpandedKeys: [],
        isArea:true,
        loading: false,
        autoExpandParent: true,
        currFlowId: '',
        currFlowName: '',
        disable: true,
        visible: false,
        areaTree: [],
        rightClickSelectedKey: '',
        model: {},
        dropTrigger: '',
        depart: {},
        columns: columns,
        disableSubmit: false,
        checkedKeys: [],
        currentProjectId:'',
        selectedKeys: [],
        autoIncr: 1,
        currSelected: {},
        form: this.$form.createForm(this),
        labelCol: {
          xs: {span: 24},
          sm: {span: 5}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16}
        },
        graphDatasource: {
          nodes: [],
          edges: []
        },
        validatorRules: {
            name: {rules: [{required: true, message: '请输入区域名称!'}]},

        },
        url: {
          delete: '/area/delete',
          edit: '/area/updateById',
          deleteBatch: '/area/deleteBatch',
          exportXlsUrl: "area/exportXls",
          importExcelUrl: "area/importExcel",
        },
        rightClickSelect:{},
      }
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      loadData() {
        this.refresh();
      },
      finish(){
        this.loadData();
      },
      loadTree() {
        var that = this
        that.areaTree = []
          queryAreaTreeList().then((res) => {
          if (res.success) {
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.areaTree.push(temp)
            }
            console.log("@@@@@@@@@@",this.areaTree)
            this.loading = false
          }
        })
      },
      setThisExpandedKeys(node) {
        if (node.children && node.children.length > 0) {
          this.iExpandedKeys.push(node.key)
          for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
        }
      },
      refresh() {
        this.loading = true
        this.loadTree()
      },
      // 右键操作方法
      rightHandle(node,row) {
        this.dropTrigger = 'contextmenu'
        if(node.node.dataRef.isArea == 0){
          this.isArea=false
        }else{
          this.isArea=true
        }
          this.rightClickSelectedKey = node.node.eventKey
      },
      onExpand(expandedKeys) {
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.iExpandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      // 右键点击下拉框改变事件
      dropStatus(visible) {
        if (visible == false) {
          this.dropTrigger = ''
        }
      },
      // 右键店家下拉关闭下拉框
      closeDrop() {
        this.dropTrigger = ''
      },
      batchDel: function () {
        let that = this
        if (this.checkedKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')
        } else {
          this.$confirm({
            title: '确认删除',
            content: '删除区域会删除区域下的项目，确定要删除所选中的 ' + that.checkedKeys.length + ' 条数据?',
            onOk: function () {
              httpAction(that.url.deleteBatch,that.checkedKeys,'post').then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadTree()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              })
            }
          })
        }
      },
      onCheck(checkedKeys, info) {
        this.checkedKeys = checkedKeys.checked
      },
      onSelect(selectedKeys, e) {
        let record = e.node.dataRef
        this.currSelected = Object.assign({}, record)
        this.model = this.currSelected
        this.selectedKeys = [record.key]
        this.model.parentId = record.parentId
        this.setValuesToForm(record)
      },
      // 触发onSelect事件时,为区域树右侧的form表单赋值
      setValuesToForm(record) {
        this.form.getFieldDecorator('fax', {initialValue: ''})
        this.form.setFieldsValue(pick(record, 'name', 'sort', 'status', 'remark'))
      },
      onClearSelected() {
        this.checkedKeys = []
        this.currSelected = {}
        this.form.resetFields()
        this.selectedKeys = []
      },

      handleAddProject(){
        let key = this.currSelected.key
        if (!key) {
          this.$message.warning('请先选中一个项目!')
          return false
        }
        this.$refs.selectProjectModal.setAreaId(this.currSelected.key)
        this.$refs.selectProjectModal.formVisible = true
        this.$refs.selectProjectModal.title = '添加项目区域'
      },
      bindProject(){
        this.$refs.selectProjectModal.setAreaId(this.rightClickSelectedKey)
        this.$refs.selectProjectModal.formVisible = false
      },
      changeName(){
        this.$refs.areaModal.changeAreaName(this.rightClickSelectedKey)
      },
      handleDelete() {
          let that = this
          deleteAction(that.url.delete, {id: that.rightClickSelectedKey}).then((res) => {
              if (res.success) {
                  that.$message.success(res.message)
                  that.loadTree()
                  that.onClearSelected()
              } else {
                  that.$message.warning(res.message)
              }
          })
      },

      getFlowGraphData(node) {
        this.graphDatasource.nodes.push({
          id: node.id,
          text: node.flowNodeName
        })
        if (node.children.length > 0) {
          for (let a = 0; a < node.children.length; a++) {
            let temp = node.children[a]
            this.graphDatasource.edges.push({
              source: node.id,
              target: temp.id
            })
            this.getFlowGraphData(temp)
          }
        }
      },
    },
    created() {
      this.currFlowId = this.$route.params.id
      this.currFlowName = this.$route.params.name
      // this.loadTree()
    },

  }
</script>
<style scoped>
  .ant-card-body .table-operator {
    margin: 15px;
  }

  .anty-form-btn {
    width: 100%;
    text-align: center;
  }

  .anty-form-btn button {
    margin: 0 5px;
  }

  .anty-node-layout .ant-layout-header {
    padding-right: 0
  }

  .header {
    padding: 0 8px;
  }

  .header button {
    margin: 0 3px
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }

  #app .desktop {
    height: auto !important;
  }

  /** Button按钮间距 */
  .ant-btn {
    margin-left: 3px
  }
</style>